﻿define(function(require,exports,module){
	require("dcs/draw/js/jqxcore.js");
	require("dcs/draw/js/jqxdraw.js");
	require("resource/js/easyui/easyloader.js");
	var ajax = require("resource/js/component/ajax.js");
	var sectionId = sessionStorage.getItem('sectionId');
	var workAreaId = null;
	var darwLastTime = null;
	var gridLastData = {};
	/** 3m = 60px */
	var metre = 3;
	
	/** 1px=3 / 60 = 0.05m */
    var pixel = metre / 60;
    /** 轨迹长度2m */
    var TrackLength = 2;
    /** 轨迹长度所占的像素 */
    var gridPixel = TrackLength / pixel;
    /** 网格数量 */
    var gridNumber = gridPixel / 2;
    /** 网格大小为2px */
    var gridSize = 2;
    /** 长半径a=6378137 */
    var a = 6378137;
    /** 短半径b=6356752.3142 */
    var b = 6356752.3142;
    /** 扁率f=1/298.2572236 */
    var f = 1 / 298.2572236;
    
    var cornersLngLat=[];
    
    var obtainGridList=[];
    
    var vehicleCoordinateAll = [];
    
    var vehicleAllList = [];
    
    /** 轨迹所有经纬度坐标 */
    var locusgridLngLat =[];
    
    var workAreaId = null;
    
    var dataJson = {};
    
    var drawPathArr = [];
    
    /** 屏幕中心点经纬度 */
    var darwCenterPointLngLat = {}; 
    
    var scrollFlag = false;
    
    /** 拖拽X坐标 */
    var xdragDrop = 0; 
    
    /** 拖拽Y坐标 */
    var ydragDrop = 0; 
    
    var twoFlag = true;
    
    var drawWidth = $($("#draw")).width(); 
    var drawHeight = $($("#draw")).height();
    
    var renderer = null;
	
    /**
     * 根据中心点经纬度计算四角经纬度的公式
     *
     */
    
    function computerThatLonLat(lon, lat, brng, dist) {
        var alpha1 = rad(brng);
        var sinAlpha1 = Math.sin(alpha1);
        var cosAlpha1 = Math.cos(alpha1);

        var tanU1 = (1 - f) * Math.tan(rad(lat));
        var cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1));
        var sinU1 = tanU1 * cosU1;
        var sigma1 = Math.atan2(tanU1, cosAlpha1);
        var sinAlpha = cosU1 * sinAlpha1;
        var cosSqAlpha = 1 - sinAlpha * sinAlpha;
        var uSq = cosSqAlpha * (a * a - b * b) / (b * b);
        var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

        var cos2SigmaM=0;
        var sinSigma=0;
        var cosSigma=0;
        var sigma = dist / (b * A), sigmaP = 2 * Math.PI;
        while (Math.abs(sigma - sigmaP) > 1e-12) {
            cos2SigmaM = Math.cos(2 * sigma1 + sigma);
            sinSigma = Math.sin(sigma);
            cosSigma = Math.cos(sigma);
            var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
                    - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
            sigmaP = sigma;
            sigma = dist / (b * A) + deltaSigma;
        }

        var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
        var lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
                (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
        var lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
        var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
        var L = lambda - (1 - C) * f * sinAlpha
                * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

        var revAz = Math.atan2(sinAlpha, -tmp); // final bearing
        cornersLngLat.push({
        	lng:Number(Number(lon)+Number(deg(L))),
        	lat:deg(lat2)
        });
    }
	
    /**
     * 度换成弧度
     *
     * @param d
     *            度
     * @return 弧度
     */
    function rad(d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 弧度换成度
     *
     * @param x
     *            弧度
     * @return 度
     */
    function deg(x) {
        return x * 180 / Math.PI;
    }
	
    /**
     * 绘制背景网格
     *
     */
    
	function initPage(){
		var w=$("#draw").width();
		var h=$("#draw").height();
		var tmp = 100;
		var i = h/tmp;
		for(j=0;j<i;j++){
			renderer.line(0, j*tmp,w,j*tmp, { stroke: '#ccc', 'stroke-width': 0.5 });
		}
		i = w/tmp;
		for(j=0;j<i;j++){
			renderer.line(j*tmp,0,j*tmp,h, { stroke: '#ccc', 'stroke-width': 0.5 });
		}
	}

	/**
     * 画布拖拽处理
     *
     */
	
	var newgrad = function(xSesult,ySesult){
		//给拖拽的坐标赋值
		xdragDrop += xSesult;
		ydragDrop += ySesult
		
		var line = $("#draw svg line");
		var circle = $("#draw svg circle");
		var pileKey = $(".pileKey");
		var rect = $("#draw svg rect");
		var newgradarr = [];
		
		for(var i=0;i<line.length;i++){
			var darwLine = $(line[i]).attr("flag");
			if(darwLine){
				newgradarr.push(line[i]);
			}
		}
		
		//拖动页面路桩点的坐标
		for(var k=0;k<circle.length;k++){
			var cx = $(circle[k]).attr("cx");
			var cy = $(circle[k]).attr("cy");
			$(circle[k]).attr("cx",Number(cx)+Number(xSesult));
			$(circle[k]).attr("cy",Number(cy)+Number(ySesult));
			$(pileKey[k]).css("left",Number(cx)+Number(xSesult));
			$(pileKey[k]).css("top",Number(cy)+Number(ySesult));
		}
		
		//拖动页面路桩的坐标
		for(var n=0;n<newgradarr.length;n++){
			var x1 = $(newgradarr[n]).attr("x1");
			var y1 = $(newgradarr[n]).attr("y1");
			var x2 = $(newgradarr[n]).attr("x2");
			var y2 = $(newgradarr[n]).attr("y2");
			$(newgradarr[n]).attr("x1",Number(x1)+Number(xSesult));
			$(newgradarr[n]).attr("x2",Number(x2)+Number(xSesult));
			$(newgradarr[n]).attr("y1",Number(y1)+Number(ySesult));
			$(newgradarr[n]).attr("y2",Number(y2)+Number(ySesult));
		}
		
		//拖动页面时轨迹的坐标
		for(var j=0; j< rect.length;j++){
			var x1 = $(rect[j]).attr("x");
			var y1 = $(rect[j]).attr("y");
			$(rect[j]).attr("x",Number(x1)+Number(xSesult));
			$(rect[j]).attr("y",Number(y1)+Number(ySesult));
		}
		
		//拖动页面时摊铺车的坐标
		var tanpucar = $(".tanpucar");
		tanpucar.each(function(){
			var toplist = $(this).css("top");
			var leftlist = $(this).css("left");
			var top = toplist.substring(0,(toplist).indexOf("p"));
			var left= leftlist.substring(0,(leftlist).indexOf("p"));
			$(this).css({
				top:Number(top) + Number(ySesult),
				left:Number(left) + Number(xSesult)
			});
		});
		
	};
	
	/**
     * 拖动函数
     *
     */
	
	function Mover(title) {
        this.obj = title;
        this.startx = 0;
        this.starty;
        this.startLeft;
        this.startTop;
        this.mainDiv = title.parentNode;
        var that = this;
        this.isDown = false;
        this.movedown = function (e) {
            e = e ? e : window.event;
            if (!window.captureEvents) {
                this.setCapture();
            }  //事件捕获仅支持ie
//            函数功能：该函数在属于当前线程的指定窗口里设置鼠标捕获。一旦窗口捕获了鼠标，
//            所有鼠标输入都针对该窗口，无论光标是否在窗口的边界内。同一时刻只能有一个窗口捕获鼠标。
//            如果鼠标光标在另一个线程创建的窗口上，只有当鼠标键按下时系统才将鼠标输入指向指定的窗口。
//            非ie浏览器 需要在document上设置事件
            that.isDown = true;
            that.startx = e.clientX;
            that.starty = e.clientY;
            that.startLeft = parseInt(that.mainDiv.style.left);
            that.startTop = parseInt(that.mainDiv.style.top);
        }
        this.move = function (e) {
            e = e ? e : window.event;
            if (that.isDown) {
                that.mainDiv.style.left = e.clientX - (that.startx - that.startLeft) + "px";
                that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px";
            }
        }
        this.moveup = function (e) {
            that.isDown = false;
            if (!window.captureEvents) {
                this.releaseCapture();
            } //事件捕获仅支持ie
            var xSesult = e.clientX - that.startx;
            var ySesult = e.clientY - that.starty;
            newgrad(xSesult,ySesult);
            if(metre<300){
            	roadPath(drawPathArr,xSesult,ySesult);
            }
            
        }
        this.obj.onmousedown = this.movedown;
        this.obj.onmousemove = this.move;
        this.obj.onmouseup = this.moveup;

        //非ie浏览器
        document.addEventListener("mousemove", this.move, true);
    }
	
	 /**
     * 绘制路辅
     *
     */
	
	var roadPath = function(option,xli,yli){
		var topArr = [];
		var bottomArr = [];
		for(var i=0; i<option.length-1;i++){
			if(xli) option[i].x = Number(option[i].x) + (Number(xli));
			if(yli) option[i].y = Number(option[i].y) + (Number(yli));
			var roadWidth = (option[i].roadWidth * (60 / metre)) / 2;
			// x轴的斜率，x轴的斜率等于0，说明两点是一条平行线，高度相等
			var xSlope = (option[i].y -  option[i+1].y) / (option[i].x -  option[i+1].x);
			if( xSlope != 0){
				var ySlope = -(1 / xSlope);
				if(ySlope > 0){
					var xLuFu = Math.ceil(-1 /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].x);
					var xLuFu1 = Math.ceil(1 /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].x);
					var yLuFu = Math.ceil(-ySlope /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].y);
					var yLuFu1 = Math.ceil(ySlope /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].y);
				}else{
					var xLuFu = Math.ceil(1 /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].x);
					var xLuFu1 = Math.ceil(-1 /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].x);
					var yLuFu = Math.ceil(ySlope /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].y);
					var yLuFu1 = Math.ceil(-ySlope /  Math.sqrt(1 + ySlope * ySlope)*roadWidth + option[i].y);
				}
			}
			
			if(xSlope == 0){
				xLuFu  = option[i].x;
				xLuFu1 = option[i].x;
				yLuFu  = option[i].y - roadWidth;
				yLuFu1 = option[i].y + roadWidth
			}
			topArr.push(xLuFu +","+ yLuFu);
			bottomArr.unshift(xLuFu1 + "," + yLuFu1);
		}
		var roadSvg = topArr.concat(bottomArr);
		var roadSvgStrings = "";
        for(var k=1;k<roadSvg.length;k++){
        	if(k==roadSvg.length-1){
        		roadSvgStrings += roadSvg[k];
        	}else{
        		roadSvgStrings += roadSvg[k] + " ";
        	}
        }
        if($("path").length==0){
        	renderer.path("M "+roadSvg[0]+" L "+roadSvgStrings+" Z", { stroke: 'rgba(172, 172, 172, 0.3)', fill: 'rgba(172, 172, 172, 0.3)' });
        }else{
        	$("path").attr("d","M "+roadSvg[0]+" L "+roadSvgStrings+" Z");
        }
	}
	
	/**
     * 绘制路桩，路桩点
     *
     */
	
    var darwObtainLine = function(option){
    	drawPathArr = option;
        var xWidth  =  $("body").width();
    	var yHeight =  $("body").height();
    	$("#draw svg").width(xWidth);
		$(renderer.renderer.canvas).width(xWidth);
		renderer.renderer.canvas.width=renderer.renderer.canvas.height;
		
    	$("#draw svg").height(yHeight);
		$(renderer.renderer.canvas).height(yHeight);
		renderer.renderer.canvas.height=renderer.renderer.canvas.height;

		for(var i=0; i<option.length-1;i++){
    		renderer.line(option[i].x,option[i].y,option[i+1].x,option[i+1].y,{ stroke: 'blue', 'stroke-width': 5, flag:true });
    	}
		
		if(metre<300){
			for(var i=0; i<option.length;i++){
				renderer.circle(option[i].x,option[i].y,6,{fill:'lightblue',stroke:'darkblue' });
				$("<div class='pileKey'>"+option[i].pileKey+"</div>").appendTo("#draw").css({
					position: "absolute",
					left:option[i].x,
					top:option[i].y,
					fontSize:"12px"
				});
			}
			roadPath(option);
		}
		
    	var mover = new Mover(document.getElementById("draw"));
    };
	
    /**
     * 所有经纬度转换为页面xy坐标
     *
     */
    
    var getCoordinate = function(data,Roadpile,res,length){
    	var drawWidth = $("#draw").width(); 
	    var drawHeight = $("#draw").height();
    	var scaleX = Math.abs(((cornersLngLat[1].lng - cornersLngLat[0].lng)*3600) / drawWidth);
    	var scaleY = Math.abs(((cornersLngLat[0].lat - cornersLngLat[3].lat)*3600) / drawHeight);
    	var screenX  = (data.lng-cornersLngLat[0].lng)*3600/scaleX;
    	var screenY  = (Number(cornersLngLat[0].lat)-Number(data.lat))*3600/scaleY;
    	
    	screenX = Math.ceil(screenX);
    	screenY = Math.ceil(screenY);
    	if(screenX % 2 != 0){
    		screenX = screenX + 1;
    	}
    	if(screenY % 2 != 0){
    		screenY = screenY + 1;
    	}
    	
    	if(Roadpile==1){
    		obtainGridList.push({
    			x:screenX,
    			y:screenY,
    			pileKey:data.pileKey,
    			roadWidth:data.roadWidth
    		});
    	}else{
    		vehicleCoordinateAll.push({
				x:screenX,
				y:screenY,
				runSpeed:data.runSpeed, //速度
				temperature:data.temperature //温度
				
			});
    	}
    	
    	if(res == length-1 ){
    		darwGridLine(vehicleCoordinateAll);
			timerFlag = false;
    	}
    	
    }
    
    /**
     *  路桩经纬度转换x,y坐标
     * 
     */
    
    var obtainGrid = function(data,index,length){
    	getCoordinate(data,1);
    	if(index==length){
    		darwObtainLine(obtainGridList);
    	}
    };
    
    
    /**
     * 查询所有路桩
     *
     */
    var getRoadPile = function(){
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			for(var k in data){
    				obtainGrid(data[k],Number(k)+1,data.length);
    			}
    			scrollFlag = true;
    		}
    	}).post(BASEPATH + '/dcs/intface/queryPileKey.htm', {sectionId:sectionId});
    }
    
    
    /**
     * 根据中心点计算四个边角经纬度
     *
     */
    var lngLatCount = function(data){
    	var drawWidth = $($("#draw")).width(); 
	    var drawHeight = $($("#draw")).height();
	    var wHalf = drawWidth/2;
	    var hHalf = drawHeight/2;
	    /** 两点之间的距离 */
	    var dist =  Math.sqrt(wHalf * wHalf + hHalf * hHalf)*pixel; 
	    /** 两点之间的夹角 */
	    var brng = Math.atan(wHalf/hHalf)* (180/Math.PI);
	    var angle = [360-brng,brng,180-brng,180+brng]
	    for(var i=0;i<angle.length;i++){
	        computerThatLonLat(data.lng, data.lat, angle[i], dist);
	    }
	    getRoadPile();
    }
    
    /**
     *  获取中心点的经纬度
     * 
     */
    var getCenterPoint = function(){
    	var option={
    			time:getCurrentTime(new Date()),
    			sectionId:sectionId
    	};
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			darwCenterPointLngLat = {
    				lat: data.lat,
    				lng: data.lng
        		};
    			lngLatCount(darwCenterPointLngLat);
    		}
    	}).post(BASEPATH + '/dcs/intface/findCenterCoor.htm', option);
    };
    
    /**
     *  摊铺机边数颜色值
     * 
     */
	var trackNumberColor = {
			"1":"#c5d3ef",
			"2":"#88aeec",
			"3":"#5894f0",
			"4":"#196df1",
			"5":"#0048c0",
			"6":"#c256fa",
			"7":"#a215eb",
			"8":"#8e15eb",
			"9":"#6e0aca",
			"10":"#6af3a6",
			"11":"#61d996",
			"12":"#44b27e",
			"13":"#069255",
			"14":"#008700",
			"15":"#005d03",
			"16":"#ff5119",
			"17":"#c31405",
			"18":"#611801",
			"19":"#360200",
			"20":"#140100",
	};
	
	var speendColor = {
			"slow":"#0061ff",
			"normal":"#26ad23",
			"fast":"#d51200"
	}
	
	/**
     *  轨迹经纬度转换x,y坐标
     * 
     */
	
	var gridcanvas = function(data,res){
		var timerFlag = true;
		for(var k=0;k<data.construction.length;k++){
			getCoordinate(data.construction[k],0,k,data.construction.length);
		}
		darwGridLine(vehicleCoordinateAll,"times","start");
		vehicleCoordinateAll =[];
		timer = window.setInterval(function(){
			if(timerFlag){
				timerFlag = false;
				vehicleCoordinateAll =[];
				dynamictrack($("#vehicleName").attr("res"),1);
			}
		},5000);
		
		
	};
	
	/**
     *  车辆运行轨迹
     * 第一参数屏幕x坐标，第二参数屏幕y点坐标，第三参数当前温度/当前速度，第四参数判断是遍数，是温度，是速度
     */
	
	var darwRect = function(gX,gY,field,type){
		if(type){
			var rectColor = null;
			if(type=="speed"){
				var minuteSpeed = field /60;
				if(minuteSpeed < 1) rectColor = speendColor["slow"];
	 			if(minuteSpeed >= 1 && minuteSpeed <= 4) rectColor = speendColor["normal"];
	 			if(minuteSpeed > 4) rectColor = speendColor["fast"]; 
			}else{
				if(field < 140)  rectColor = speendColor["slow"];
				if(field >= 140) rectColor = speendColor["normal"];
			}
			
			if(!dataJson[Math.ceil(gX) +","+ Math.ceil(gY)]){
				var grid = renderer.rect(Math.ceil(gX), Math.ceil(gY), 2, 2, { fill:rectColor,stroke: rectColor});
				dataJson[Math.ceil(gX) +","+ Math.ceil(Number(gY))] = grid;
			}else{
				var lineID = $(dataJson[Math.ceil(gX) +","+ Math.ceil(gY)]);
				lineID.attr("fill",rectColor);
				lineID.attr("stroke",rectColor);
			}
		}else{
			if(!dataJson[Math.ceil(gX) +","+ Math.ceil(gY)]){
				var grid = renderer.rect(Math.ceil(gX+xdragDrop), Math.ceil(gY+ydragDrop), 2, 2, { fill:trackNumberColor[1],stroke: trackNumberColor[1],num:1});
				dataJson[Math.ceil(gX) +","+ Math.ceil(Number(gY))] = grid;
			}else{
				var lineID = $(dataJson[Math.ceil(gX) +","+ Math.ceil(gY)]);
				var fillColor = trackNumberColor[Number(lineID.attr("num")) + 1];
				lineID.attr("fill",fillColor);
				lineID.attr("stroke",fillColor);
				lineID.attr("num",Number(lineID.attr("num")) + 1);
			}
		}
	}
	
	/**
     *  摊铺机一秒执行一次
     * 
     */
	var timer = null;
	
	
	var darwGridLine = function(data,type,state){
		if(data.length!=0){//gridLastData
			if(state){
				gridLastData = data[data.length-1];
			}
			for(var i=0;i<data.length;i++){
				if(i<data.length-1){
					var xend = data[i].x - data[i+1].x;
					var yend = data[i].y - data[i+1].y;
				}else{
					if(data.length==1){
						var xend = gridLastData.x - data[i].x;
						var yend = gridLastData.y - data[i].y;
					}else{
						var xend = data[i-1].x - data[i].x;
						var yend = data[i-1].y - data[i].y;
					}
				}
				var mouseX = data[i].x;
				var mouseY = data[i].y;
				var xValue = Math.abs(xend) / gridSize;
				var yValue = Math.abs(yend) / gridSize;
				var xAverage = Math.abs(yend) / xValue;
				var yAverage = Math.abs(xend) / yValue;
				if(Math.abs(yend) < Math.abs(xend)){
					var mouseGrid = mouseY - gridPixel / 2;//gridPixel  轨迹长度所占的像素
					for(var m=0;m < xValue;m++){
						for(var k=0;k<gridNumber;k++){
							if(xend < 0){
								var gX = mouseX + gridSize*m;
							}else{
								var gX = mouseX - gridSize*m;
							}
							if(yend < 0){
								var gY = (mouseGrid+gridSize*k) + m*xAverage;
							}else{
								var gY = (mouseGrid+gridSize*k) - m*xAverage;
							}
							gY = Math.ceil(gY);
							if(gY % 2 != 0){
								gY = gY + 1;
				    		}
							
							//速度
							if(type=="speed"){
								darwRect(gX,gY,data[i].runSpeed,"speed");
							}
							
							//温度
							if(type=="temperature"){
								darwRect(gX,gY,data[i].temperature,"temperature");
							}
							
							//遍数
							if(type="times"){
								darwRect(gX,gY);
							}
						}
					}
				}else{
					var mouseGrid = mouseX - gridPixel / 2;//gridPixel  轨迹长度所占的像素
					for(var m=0;m < Math.ceil(yValue);m++){
						for(var k=0;k<gridNumber;k++){
							if(xend < 0){
								var gX = (mouseGrid+gridSize*k) - m*yAverage;
							}else{
								var gX = (mouseGrid+gridSize*k) + m*yAverage;
							}
							if(yend < 0){
								var gY =  mouseY - gridSize*m;
							}else{
								var gY =  mouseY + gridSize*m;
							}
							darwRect(gX,gY);
						}
					}
				}
			}
			if($(".vehicle").html()=="" && data.length!=0){
				$("<div class='tanpucar'><div class='matchVehicleName'>"+$("#vehicleName").text()+"</div>" +
				"<img src='"+BASEPATH+"/resource/images/carimage.png' /></div>").appendTo($(".vehicle")).css({
					top:(data[data.length-1].y - gridPixel / 2)-3 + ydragDrop,
					left:data[data.length-1].x + xdragDrop
				});
			}else{
				$(".vehicle img").css({
					top:(data[data.length-1].y - gridPixel / 2) + ydragDrop,
					left:data[data.length-1].x + xdragDrop
				});
			}
			
		}
	}
	
	
	/**
     *  初始化获取所有车辆每个点的经纬度，温度，速度,车辆id
     * 
     */
	
	var dynamictrack = function(conId,isFirst){
		if(isFirst==1){
			var option={
					conId:conId,
					sectionId:sectionId,
	    			isFirst:isFirst,
	    			time:darwLastTime
	    	};
		}else{
			var option={
					conId:conId,
					sectionId:sectionId,
					isFirst:0
			};
		}
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			locusgridLngLat = data;
    			var length = data.construction.length;
    			if(length) darwLastTime = data.construction[length-1].time;
    			if(twoFlag){
    				twoFlag = false;
    				gridcanvas(data,0);
    			}else{
    				gridcanvas(data,1);
    			}
    		}
    	}).post(BASEPATH + '/dcs/paverConstructionAction/queryRealTimeTrajectory.htm', option);
	}
	
	
	/**
     *  放大缩小
     * 
     */
	
	var scrollFunc = function (e,data) {
		if(scrollFlag){
			scrollFlag = false;
			e = e || window.event;  
	        if (e.wheelDelta || e.type=="click") {  //判断浏览器IE，谷歌滑轮事件          
	        	$(document).off("onmousewheel DOMMouseScroll");
	        	if (e.wheelDelta > 0 || data=="up") { //当滑轮向上滚动时  
	                if(metre==3){
	                	scrollFlag = true;
	                	return;
	                } 
	            	if(metre>3){
	            	   metre=metre/10;
				   }
	            }  
	            if (e.wheelDelta < 0 || data=="down") { //当滑轮向下滚动时  
	            	if(metre==300){
	            		scrollFlag = true;
	            		return;
	            	} 
	            	if(metre<300){
	                	 metre=metre*10;
					 }
	            }

	            $(".amap-scale-text").text(metre+"米");
	            pixel = metre/60;
	            xdragDrop = 0;
	            ydragDrop = 0;
	            window.clearInterval(timer); 
	            cornersLngLat = [];
	            obtainGridList = [];
	            vehicleCoordinateAll = [];
	            dataJson =[];
	            $("#draw svg").html("");
	            $(".pileKey").remove();
	            $(".tanpucar").remove();
	            initPage();
	            lngLatCount(darwCenterPointLngLat);
	            vehicleListDraw(vehicleAllList);
	        } else if (e.detail) {  //Firefox滑轮事件  
	            if (e.detail> 0) { //当滑轮向下滚动时  
	               alert('下滚')
	            }  
	            if (e.detail< 0) { //当滑轮向上滚动时  
	                alert('上滚')  
	            }  
	        } 
		}
    } 
	
	if(navigator.userAgent.indexOf("Firefox")>0){
		if(document.addEventListener){
			document.addEventListener('DOMMouseScroll',scrollFunc,false);
		}
	}else{
		document.onmousewheel = scrollFunc;
	}
    
	
    /**
     *  点击工区，弹窗
     * 
     */
	
    var addDialogInit = function(url,id,state){
    	$("#editdlg").dialog({
			//title:config.name+"增加",
			href:url,
			onLoad:function(){
				window.clearInterval(timer);
				cornersLngLat = [];
	            obtainGridList = [];
	            vehicleCoordinateAll=[];
	            dataJson =[];
	            $("#draw svg").html("");
	            $(".pileKey").remove();
	            $(".tanpucar").remove();
				$("#draw").jqxDraw();
				renderer = $($("#draw")).jqxDraw('getInstance');
				$(renderer.renderer.canvas).removeAttr("overflow");
				initPage();
				getCenterPoint();
		    	getWorkLayer();
		    	vehicleList(id);
		    	if(state==0){
		    		$("#zoom_back").hide();
		    	}
		    	
		    	//返回
		    	$("#zoom_back").on("click",function(){
		        	$("#editdlg").dialog("close");
		        });
		    	
		    	//鼠标点击放大按钮
		    	$("#zoom_enlarge").click(function(){
		    		scrollFunc(null,"up");
		    	});
		    	
		    	//鼠标点击缩小按钮
		    	$("#zoom_reduce").click(function(){
		    		scrollFunc(null,"down");
		    	});
		    }
		});
		$("#editdlg").dialog("open");
    }
    
    /**
     *  查询工作层级
     * 
     */
	var getWorkLayer = function(){
    	var option={
    			time:getCurrentTime(new Date()),
    			sectionId:sectionId,
    	};
		ajax.init().success(function(code,msg,data){
    		if(code==0){
    			$(".vehicleInfo").prepend("<div class='workLayer' id="+data.layerId+"><span>"+data.layerName+"</span><span>工作层级</span></div>");
    			
    		}
    	}).post(BASEPATH + '/dcs/intface/findLayerByTime.htm', option);
	};
    
    /**
     *  车辆信息
     * 
     */
	
    var vehicleInfo = function(conId){
    	var options = {
    			sectionId:sectionId,
    			conId:conId,
    			par:"now",
    			time:getCurrentTime(new Date())
    			
    	}
    	$(".vehicleInfo ul").html("");
    	ajax.init().success(function(code,msg,data){
    		if(data.construction && code==0){
    			
    			$("<li><span>"+trim(data.construction.conVid)+"</span><span>车辆编号</span></li>" +
    			  "<li><span>"+trim(data.construction.conName)+"</span><span>车辆名称</span></li>" +
    			  "<li><span>"+trim(data.construction.speedNow)+"</span><span>行驶速度</span></li>" +
    			  "<li><span>"+trim(data.construction.mileage)+"</span><span>当前里程</span></li>" +
    			  "<li><span>"+trim(data.construction.time)+"</span><span>最后时间</span></li>").appendTo($(".vehicleInfo ul"));
    		}
    	}).post(BASEPATH + '/dcs/intface/findSectionAndConstructionInfo.htm', options);
    }
    
    /**
     *  车辆列表
     * 
     */
    
    
    var vehicleListDraw  = function(data){
    	$(".vehicleList ul").html("");
    	for(var k in data){
			if(data[k].vehicleType == "01"){
				$("<li id="+data[k].id+">"+data[k].vehicleName+"</li>").appendTo($(".vehicleList ul")).on("click",function(){
					$(this).addClass("current").siblings().removeClass("current");
					$("#vehicleName").text($(this).text());
					$("#vehicleName").attr("res",$(this).attr("id"));
					vehicleInfo($(this).attr("id"));
					window.clearInterval(timer);
					$("#draw svg rect").remove();
					$(".vehicle").html("");
					dataJson= {};
					$(".vehicle").html("");
					twoFlag = true;
					dynamictrack($(this).attr("id"),0);
					$(".vehicleList").hide();
				});
			}
		}
    	
    	$(".vehicleList li").first().click();
		$(".vehicleSelect").unbind("click");
		$(".vehicleSelect").on("click",function(){
			$(".vehicleList").toggle();
		});
		
		$(".darwtab li").on("click",function(){
			$(this).addClass("current").siblings().removeClass("current");
    		$(this).children(".tablevel").show();
    		$(this).siblings().children(".tablevel").hide();
    	});
        $(".darwtab li").first().click();
        
        //点击速度
        $("#paverSpeed>span").on("click",function(){
        	window.clearInterval(timer);
			$("#draw svg rect").remove();
			$(".vehicle").html("");
			dataJson= {};
        	darwGridLine($("#vehicleName").attr("res"),vehicleCoordinateAll,"speed");
        });
        
        //点击温度
        $("#paverTemperature>span").on("click",function(){
        	window.clearInterval(timer);
			$("#draw svg rect").remove();
			$(".vehicle").html("");
			dataJson= {};
        	darwGridLine($("#vehicleName").attr("res"),vehicleCoordinateAll,"temperature");
        });
        
      //点击遍数
        $("#frequency>span").on("click",function(){
        	window.clearInterval(timer);
			$("#draw svg rect").remove();
			$(".vehicle").html("");
			dataJson= {};
			darwGridLine($("#vehicleName").attr("res"),vehicleCoordinateAll);
        });
    	
    }
    
    
    var vehicleList = function(workAreaId,vehicleCoordinateAll){
    	
    	if(!workAreaId)  workAreaId=sectionId;
    	var option = {
    			vehicle_type:"01",
    			workAreaId:workAreaId
    	};
    	ajax.init().success(function(code,msg,data){
    		if(code==0){
    			vehicleAllList = data;
    			vehicleListDraw(data);
    			
    		}
    	}).post(BASEPATH + '/dcs/intface/querySysConstructionVehicleByAreaId.htm',option);
    }
    
    
    var trim = function(data){
    	return data || "暂无";
    }
    
    /**
     *  查询当前时间
     * 
     */
    
    var getCurrentTime = function(currentTime){
    	var setDate = currentTime.setDate(currentTime.getDate() - 12);
    	setDate = new Date(setDate);
    	var time = setDate.getFullYear() +"-"+ Number(setDate.getMonth()+1) +"-"+ setDate.getDate() +" "+
    	setDate.getHours() +":"+ setDate.getMinutes()+":"+ setDate.getSeconds();
    	/*var time = currentTime.getFullYear() +"-"+ Number(currentTime.getMonth()+1) +"-"+ currentTime.getDate() +" "+
    	currentTime.getHours() +":"+ currentTime.getMinutes()+":"+ currentTime.getSeconds();*/
    	return time;
    }
    
    /**
     *  获取工区
     *  有工区打开工区，没有工区打开画布
     */
	var getWorkArea = function(){
		ajax.init().success(function(code,msg,data){
    		if(code==0){
    			var url = BASEPATH+"/view/dcs/draw/add";
    			if(data.length==0){
					addDialogInit(url,sectionId,0);
    			}else{
    				$(".workAreaSelect").show();
    				for(var k in data){
    					$("<li id="+data[k].sectionId+">"+data[k].workAreaName+"</li>").appendTo($(".workAreaSelect ul")).on("click",function(){
    						addDialogInit(url,$(this).attr("id"));
//    						workAreaId = $(this).attr("id");
    					});
    				}
    			}
    			
    		}
    	}).post(BASEPATH + '/dcs/section/queryWorkArea.htm', {sectionId:sectionId});
	};
    
    
    exports.trans = function(){
    	using(["parser","dialog"],function(){
    		getWorkArea();
    	});
	}
});
